package com.zhangwei.liwushuo.fragment;


import com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;
import com.zhangwei.liwushuo.R;

import org.androidannotations.annotations.EFragment;

import java.io.File;
import java.io.IOException;

/**
 * api 4.4 底层使用 okhttp 应用框架层
 */
//HttUrlConnction

@EFragment(R.layout.fragment_me)
public class MeFragment extends BaseFragment {
    Call call;

    //    String str = "1" + "2" + "3";
//    StringBuffer sb = new StringBuffer();
    @Override
    public void initView() {
        super.initView();
        /**
         * 第一步创建 OkHttpClient 对象
         * 第二步创建 Request对象
         * 第三步创建  Call对象
         * 第四步 加入请求
         * 第五步  在生命周期的onstop  取消请求 call.cancel();
         *
         */
        OkHttpClient client = new OkHttpClient();
        final Request request = new Request.Builder().url("").build();
        call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                
            }

            @Override
            public void onResponse(Response response) throws IOException {
                String result = response.body().string();
//                byte[] bytes = response.body().bytes();
//                InputStream inputStream = response.body().byteStream();

            }
        });
    }


    private void post() {
        OkHttpClient client = new OkHttpClient();
        FormEncodingBuilder builder = new FormEncodingBuilder().add("username", "");
        RequestBody body = builder.build();
        Request request = new Request.Builder()
                .url("")
                .post(body)
                .build();

        call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {

            }

            @Override
            public void onResponse(Response response) throws IOException {
                String result = response.body().string();
//                byte[] bytes = response.body().bytes();
//                InputStream inputStream = response.body().byteStream();
            }
        });

    }

    public static final MediaType MEDIA_TYPE_MARKDOWN
            = MediaType.parse("text/x-markdown; charset=utf-8");

    private void updatefile() {
        RequestBody body = RequestBody.create(MEDIA_TYPE_MARKDOWN, new File(""));
        Request request = new Request.Builder().url("").post(body).build();
        OkHttpClient httpClient = new OkHttpClient();
    }


    @Override
    public void onStop() {
        super.onStop();
        call.cancel();
    }
}
